package org.jetnuke.modules.blog;

import org.apache.log4j.Logger;

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.jforum.util.preferences.ConfigKeys;
import net.jforum.util.preferences.SystemGlobals;

import org.apache.velocity.VelocityContext;
import org.jetnuke.common.ActionForward;
import org.jetnuke.common.IAction;
import org.jetnuke.common.IAdminInfo;
import org.jetnuke.common.IModuleInfo;
import org.jetnuke.common.IUserInfo;
import org.jetnuke.util.JetUtil;
import org.jetnuke.util.StringUtils;

public class GetResource implements IAction {
	/**
	 * Logger for this class
	 */
	private static final Logger logger = Logger.getLogger(GetResource.class);

	String file;
	int uid;

	public void setUid(int uid) {
		this.uid = uid;
	}

	public ActionForward exec(HttpServletRequest request,
			HttpServletResponse response, VelocityContext vc, IModuleInfo info,
			String op, IUserInfo ui, IAdminInfo ai) throws Exception {
		if (logger.isDebugEnabled()) {
			logger
					.debug("exec(HttpServletRequest, HttpServletResponse, VelocityContext, IModuleInfo, String, IUserInfo, IAdminInfo) - start"); //$NON-NLS-1$
		}

		String dir = SystemGlobals.getValue(ConfigKeys.ATTACHMENTS_STORE_DIR)
				+ "/blog/" + uid + "/";
		File f = new File(dir, file);
		if (!f.exists())
			return null;

		BufferedInputStream bis = new BufferedInputStream(
				new FileInputStream(f));
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		byte[] b = new byte[4096];

		while ((bis.read(b)) != -1) {
			baos.write(b);
		}
		bis.close();
		JetUtil.manageReponseCookies(vc, response);
		String mimeType = StringUtils.findMimeType(file);

		if (!"?".equals(mimeType)) {
			response.setContentType(mimeType);
			response.setContentLength(baos.size());
			response.setHeader("Expires", "0");
			response.setHeader("Content-disposition", "inline");
		} else {
			response.setContentLength(baos.size());
			response.setContentType("application/octet-stream");
			response.setHeader("Content-Disposition", "attachment;filename=\""
					+ file + "\"");
		}

		baos.writeTo(response.getOutputStream());

		if (logger.isDebugEnabled()) {
			logger
					.debug("exec(HttpServletRequest, HttpServletResponse, VelocityContext, IModuleInfo, String, IUserInfo, IAdminInfo) - end"); //$NON-NLS-1$
		}
		return null;
	}

	public void setFile(String file) {
		this.file = file;
	}

}
